<?php
/**
 * 
 *
 * @author comfiger<liuqiang@wisdudu.com>
 * @version v1.0.0
 *
 **/
namespace Home\Controller;
use Think\Controller;

class WapController extends Controller {
	protected $webservice = 'http://114.119.5.137:1001/NLockWebService.asmx?wsdl'; //接口地址
	
	public function index(){
		if(IS_GET){
			if(session('member_id')){
				$info = D('Member')->getMemberInfoById(session('member_id'));
				if(is_array($info) && count($info)){
					$this->assign('info', $info);
					$this->display('info');
				}else{
					$this->assign('error', '您还为预约房间');
					$this->display();
				}
			}else{
				$this->display();
			}
		}else if(IS_POST){
			$phone = I('post.phone') ? trim(I('post.phone')) : '';
			$card = I('post.card') ? trim(I('post.card')) : '';
			$code = I('post.code') ? trim(I('post.code')) : '';
			
			$info = D('Member')->getMemberInfoByPhone($phone, $code);
			
			if(is_array($info) && count($info)){
				session('member_id', $info['member_id']); //设置session
				session('member_nick', $info['member_nick']); //设置session
				$this->ajaxReturn(array(
					'errCode' => 1
				), 'json');
			}else{
				$this->ajaxReturn(array(
					'errCode' => 0,
					'errMsg' => '您还未预约房间'
				), 'json');
			}
		}
	}
	
	public function lout(){
		session('member_id', null); //设置session
		session('member_nick', null); //设置session
		
		$this->display('index');
	}
	
	public function info(){
		if(IS_GET){
			if(session('member_id')){
				$info = D('Member')->getMemberInfoById(session('member_id'));
				if(is_array($info) && count($info)){
					$this->assign('info', $info);
					$this->display('info');
				}else{
					$this->assign('error', '您还未预约房间');
					$this->display();
				}
			}else{
				$this->display('index');
			}
		}else if(IS_POST){
			//根据用户ID获取房间信息
			$info = D('Member')->getMemberInfoById(session('member_id'));
			//cmd 
			$cmd = I('post.cmd') ? trim(I('post.cmd')) : '';
			//pwds
			$remark = I('post.remark') ? trim(I('post.remark')) : '';
			$begintime = time();
			
			if(is_array($info) && count($info)){
				if(!empty($info['room_number'])){
					//判断是否是否有效 
					// checkin_time: 1485410400
					// leaving_time: 1485583200
					if($info['checkin_time'] < time() && $info['leaving_time'] > time()){
						$data['param4'] = date('Y-m-d', $info['checkin_time']) . ' 00:00:00';
						$data['param5'] = date('Y-m-d', $info['leaving_time']) . ' 14:00:00';
					}else if($info['checkin_time'] > time() && $info['leaving_time'] > time()){
						if($cmd == '004'){
							$data['param4'] = date('Y-m-d', $info['checkin_time']) . ' 00:00:00';
							$data['param5'] = date('Y-m-d', $info['leaving_time']) . ' 14:00:00';
						}else{
							$this->ajaxReturn(array(
								'errCode' => 0,
								'errMsg' => '不在您预约的时间内'
							), 'json');
							exit;
						}
					}else{
						$this->ajaxReturn(array(
							'errCode' => 0,
							'errMsg' => '不在您预约的时间内'
						), 'json');
					}
					//查询锁
					$lock = D('Lock')->getLockInfoByRoomNumbers($info['room_number']);
					if(is_array($lock) && count($lock)){
						if($cmd == '002' || $cmd == '003'){
							//获取日志
							$param['devicenum'] = $lock['network_nums'];
							//获取最大日志ID 
							$maxID = D('Lockopen')->getMaxJidByNetworkNums($lock['network_barcode']);
							if(empty($maxID)){
								$param['StartID'] = 0;
							}else if($maxID - 2 > 0){
								$param['StartID'] = $maxID -2;
							}else{
								$param['StartID'] = $maxID;
							}
							//获取结果
							$list = $this->CallSoapWebService('GetsOpenRecord', $param);
							//解析数据
							if(is_array($list) && count($list) && $list['result']){
								foreach($list['parameters'] as $ls){
									$times = strtotime('2014-01-01 00:00:00')+($ls['open_time'] * 60);
									if((abs($times - $begintime) <= 60) && $ls['open_type'] == '44'){ //存在记录哦
										$card_udid = dechex($ls['open_num']);
										writeLog('=== times: '. $times . ' begintime: '. $begintime . ' open_type: '. $ls['open_type'].' card_udid:'.$card_udid .' '. json_encode($ls));
										break;
									}else{
										writeLog('--- times: '. $times . ' begintime: '. $begintime . ' open_type: '. $ls['open_type'] .' '. json_encode($ls));
									}
								}
							}
						}
					}else{
						$this->ajaxReturn(array(
							'errCode' => 0,
							'errMsg' => '请不存在房间号与锁的关系'
						),'json');
					}
				}else{
					$this->ajaxReturn(array(
						'errCode' => 0,
						'errMsg' => '请输入房间号'
					), 'json');
				}
				
				$log = array(
					'room_number' => $info['room_number'],
					'user_id' => session('member_id'),
					'nickname' => '客户：'. session('member_nick'),
					'lock_id' => $lock['cmd_id'],
					'network_nums' => $lock['network_nums'],
					'cmd_time' => time(),
					'b_time' => $btime,
					'e_time' => $etime
				);
				
				switch($cmd){
					case '002':
						//获取员工信息
						if(!empty($card_udid)){
							$data['param3'] = $this->strrevtostr($card_udid); //身份证UDID
							$param['JsonStr'] = "{result:0,events:[{event:002,param1:'{$lock['network_nums']}',param2:'{$lock['cmd_id']}',param3:'{$data['param3']}',param4:'{$data['param4']}',param5:'{$data['param5']}',param6:'111111111111111111111111',param7:'11111111'}]}";
							$log['cmd'] = '发送身份证ID';
							$log['param'] = '姓名：'. $session['member_nick'] .' ID：'. $card_udid;
							$log['cmd_key'] = '002';
						}else{
							$this->ajaxReturn(array(
								'errCode' => 0
							), 'json');
						}
					break;
					case '003':
						//获取房卡信息
						if(!empty($card_udid)){
							$data['param3'] = str_pad($card_udid, 18, 'F'); //IC开UDID
							$param['JsonStr'] = "{result:0,events:[{event:003,param1:'{$lock['network_nums']}',param2:'{$lock['cmd_id']}',param3:'{$data['param3']}',param4:'{$data['param4']}',param5:'{$data['param5']}',param6:'111111111111111111111111',param7:'11111111'}]}";
							
							$log['cmd'] = '发送IC卡ID';
							$log['param'] = '房卡号：'. $card_udid;
							$log['cmd_key'] = '003';
						}else{
							$this->ajaxReturn(array(
								'errCode' => 0
							), 'json');
						}	
					break;
					case '004':
						//设置密码
						if(!empty($remark) && is_numeric($remark)){
							$data['param3'] = $this->strrevtostr($remark);
							
							$param['JsonStr'] = "{result:0,events:[{event:004,param1:'{$lock['network_nums']}',param2:'{$lock['cmd_id']}',param3:'{$data['param3']}',param4:'{$data['param4']}',param5:'{$data['param5']}',param6:'111111111111111111111111',param7:'11111111'}]}";
						}else{
							$this->ajaxReturn('请输入数字密码', 'json');
						}
						
						$log['cmd'] = '发送密码';
						$log['param'] = '密码信息：'. $remark;
						$log['cmd_key'] = '004';
					break;
				}
				
				$log['b_time'] = $data['param4'];
				$log['e_time'] = $data['param5'];
				
				$list = $this->CallSoapWebService('GPRSCMD', $param);
				
				//判断结果
				$rows = $list['events'][0]['event'];
				$log['result'] = $rows ? 0 : 1;
				//判断结果
				$row = D('Lockcmd')->addLockcmdLog($log);
				if($log['result']){
					writeLog("---> 授权成功");
					$this->ajaxReturn(array(
						'errCode' => 1,
						'errMsg' => '授权成功'
					), 'json');
				}else{
					$this->ajaxReturn(array(
						'errCode' => 0,
						'errMsg' => '授权失败'
					), 'json');
				}
			}else{
				
			}
		}
	}
	
	/**
	 * Check times
	 *
	 **/
	public function ajaxTimer(){
		//根据用户ID获取房间信息
		$info = D('Member')->getMemberInfoById(session('member_id'));
		if($info['checkin_time'] < time() && $info['leaving_time'] > time()){
			$this->ajaxReturn(array(
				'errCode' => 1,
				'errMsg' => 'Success'
			), 'json');
		}else if($info['checkin_time'] > time() && $info['leaving_time'] > time()){
			$this->ajaxReturn(array(
				'errCode' => 0,
				'errMsg' => '不在您预约的时间内'
			), 'json');
		}else{
			$this->ajaxReturn(array(
				'errCode' => 0,
				'errMsg' => '不在您预约的时间内'
			), 'json');
		}
	}
	
	/**
	 * 请求webservices接口 
	 * @param string $func 接口名称
	 * @param array $param 参数名称
	 **/
	private function CallSoapWebService($func, $param){
		if(is_array($param)){
			if($func == 'GPRSCMD'){
				$param['account'] = 'mmhome';
				$param['md5'] = strtoupper(md5($param['JsonStr'].strtoupper(md5('18002327408'))));
			}else{
				$param['account'] = 'mmhome';
				$param['md5'] = strtoupper(md5('18002327408'));
			}
		}
		
		$client = new \SoapClient($this->webservice);
		try{
			$arr = $client->__call($func, array($func => $param));
			$arr = json_decode(json_encode($arr),true);
			
			if(is_array($arr)){
				switch($func){
					case 'GetNetworkBoxStateByNum':
						
					break;
					case 'GetsOpenRecord': //获取开门日志
						$result = json_decode($arr['GetsOpenRecordResult'], true);
					break;
					case 'GPRSCMD': //控制指令
						$list = $arr['GPRSCMDResult'];
						$result = $this->ext_json_decode($list, true);
					break;
				}
				
				return $result;
			}
		}catch(Exception $e){
			$this->ajaxReturn(0, '读取数据失败');
		}
	}
	
	/**
	 * 解析JSON中没有使用双引号包含的key
	 *
	 **/
	private function ext_json_decode($str, $mode=false){
		if(preg_match('/\w:/', $str)){
			$str = preg_replace('/(\w+):/is', '"$1":', $str);
		}
		$str = str_replace("'", '"', $str);
		return json_decode($str, $mode);
	}
	
	/**
	 * 交换字符串位置
	 *
	 **/
	private function strrevtostr($string){
		if(strlen($string) < 16){
			$string = str_pad(strrev($string), 18, 'F');
			//交换位置
			$newString = "";
			for($i=0;$i<=17;$i++){
				if($i%2 == 0){
					$newString .= $string[$i+1];
				}else{
					$newString .= $string[$i-1];
				}
			}
		}else{
			$newString = str_pad($string, 18, 'F');
		}
		
		return $newString;
	}
}


   